using IStrong.EC.Web.Controllers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using IStrong.EC.ExtensionMethods;
using IStrong.EC.WebApi.Results.Repository;

namespace IStrong.EC.WebApi.Results.Controllers
{
    /// <summary>
    /// Api控制器模板
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class UnitController : BaseController
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<UnitController> _logger;

        /// <summary>
        /// 配置
        /// </summary>
        private readonly IConfiguration _config;

        /// <summary>
        /// 
        /// </summary>
        private readonly Utility _unitl;


        /// <summary>
        /// 注入服务
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="config"></param>
        public UnitController(ILogger<UnitController> logger, IConfiguration config, Utility unitl)
        {
            _logger = logger;
            _config = config;
            _unitl = unitl;
        }

        /// <summary>
        /// GET api/values
        /// </summary>
        /// <returns></returns>
        [HttpGet("areatree")]
        public JsonResult GetArea()
        {
            try
            {
                var data = _unitl.GetArea(null);

                var node = data.Where(d => d.Value.EndsWith("0000")).ToList();

                foreach (var item in node)
                {
                    item.Children = data.Where(d => !d.Value.EndsWith("0000") && d.Value.EndsWith("00") && d.Value.StartsWith(item.Value.Substring(0, 2))).ToList();
                    foreach (var itemChildren in item.Children)
                    {
                        itemChildren.Children = data.Where(d => !d.Value.EndsWith("00") && d.Value.StartsWith(itemChildren.Value.Substring(0, 4))).ToList();
                    }
                }

                return Json(node);

            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }
    }
}
